package com.itbaiyun.agent.agent;

import com.itbaiyun.agent.agent.model.AgentState;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;

import java.util.ArrayList;
import java.util.List;

/**
 * 抽象基础代理类, 用于管理代理状态和执行流程
 *
 * 提供状态转换,内存管理和基于步骤的执行循环的基础功能
 * 子类必须实现step方法
 */
@Data
@Slf4j
public abstract class BaseAgent {

    //核心属性
    private String name;

    //系统提示词
    private String systemPrompt;

    //下一步提示词
    private String nextPrompt;

    //代理状态
    private AgentState state = AgentState.IDEL;

    //执行步骤
    private int currentStep = 0;
    private int maxStep = 20;

    //LLM大模型
    private ChatClient chatClient;

    //聊天记忆(需要可以自行维护)
    private List<Message> messages = new ArrayList<>();

    /**
     * 运行代理
     */
    public void run(String userPrompt) {
        //基础校验
        if (StringUtils.isBlank(userPrompt)){
            throw new RuntimeException("Cannot run agent with empty user prompt");
        }

        if (this.state != AgentState.IDEL){
            throw new RuntimeException("Cannot run agent in non-idle state"+this.state);
        }

        //2.执行, 修改状态
        this.state = AgentState.RUNNING;
        //记录消息上下文
        messages.add(new UserMessage(userPrompt));
        //保存结果列表
        List<String> msgResult = new ArrayList<>();

        try {
            //执行循环
            for (int i = 0; i < maxStep && this.state != AgentState.FINISHED; i++) {
                currentStep++;
                //单步执行
                String stepResult = step();
                String result = "Step " + currentStep + ": " + stepResult;
                msgResult.add(result);
            }

            //检查是否超出步骤限制
            if (currentStep >= maxStep) {
                this.state = AgentState.FINISHED;
                log.error("Agent reached maximum number of steps: " + maxStep);
                msgResult.add("Terminated:Agent reached maximum number of steps: " + maxStep);
            }
        } catch (Exception e) {
            state = AgentState.ERROR;
            log.error("error executing agent", e);
        } finally {
            // 3、清理资源
            this.cleanup();
        }

    }


    /**
     * 定义单个步骤
     *
     * @return
     */
    public abstract String step();


    /**
     * 清理资源
     */
    protected void cleanup() {
        // 子类可以重写此方法来清理资源
    }
}
